package com.luohoufa.ms.apigateway.filter;

import com.luohoufa.ms.apigateway.util.CookieUtil;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_DECORATION_FILTER_ORDER;
import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE;

/**
 * 权限拦截（区分买家和卖家）
 */
@Component
public class AuthFilter extends ZuulFilter {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public String filterType() {
        return PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return PRE_DECORATION_FILTER_ORDER - 1;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        /**
         * /order/create 只能买家访问
         * /order/finish 只能卖家访问
         * /product/list 两者都可以访问
         */
//        String requestURI = request.getRequestURI();
//        if ("/order/order/create".equals(requestURI)) {
//            Cookie cookie = CookieUtil.get(request, "openid");
//            if (cookie==null || StringUtils.isEmpty(cookie.getValue())) {
//                // 没有权限
//                currentContext.setSendZuulResponse(false);
//                currentContext.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
//            }
//        }
//
//        if ("/order/order/finish".equals(requestURI)) {
//            Cookie cookie = CookieUtil.get(request, "token");
//
//            if (cookie==null || StringUtils.isEmpty(cookie.getValue())
//                    || StringUtils.isEmpty(stringRedisTemplate.opsForValue().get(cookie.getValue()))) {
//                // 没有权限
//                currentContext.setSendZuulResponse(false);
//                currentContext.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
//            }
//        }


        return null;
    }
}
